



import React from 'react';
import {
    StyleSheet,
    TouchableOpacity,
    View,
    Text,
    BackHandler,
    InteractionManager,
    Animated,
    Easing,
    Platform,
    Alert,
    Image
} from 'react-native';
import Camera from 'react-native-camera';
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');



 class qrScanner extends React.Component {
    constructor(props) {
        super(props);
        this.camera = null;
        this.state = {
            lightOn:'auto',
            show:true,//是否继续扫描二维码
            anim: new Animated.Value(0),
            camera: {
                aspect: Camera.constants.Aspect.fill,
            },
        };

     // this.params = this.props.navigation.state;

      var title=this.props.navigation.state.params.title;
      this.onBackAndroid=this.onBackAndroid.bind(this);

       
        this.isLightOn=false;

    }
     static navigationOptions = {

        /**
         *  title：标题，如果设置了这个导航栏和标签栏的title就会变成一样的，不推荐使用
            header：可以设置一些导航的属性，如果隐藏顶部导航栏只要将这个属性设置为null
            headerTitle：设置导航栏标题，推荐
            headerBackTitle：设置跳转页面左侧返回箭头后面的文字，默认是上一个页面的标题。可以自定义，也可以设置为null
            headerTruncatedBackTitle：设置当上个页面标题不符合返回箭头后的文字时，默认改成"返回"
            headerRight：设置导航条右侧。可以是按钮或者其他视图控件
            headerLeft：设置导航条左侧。可以是按钮或者其他视图控件
            headerStyle：设置导航条的样式。背景色，宽高等
            headerTitleStyle：设置导航栏文字样式
            headerBackTitleStyle：设置导航栏‘返回’文字样式
            headerTintColor：设置导航栏颜色
            headerPressColorAndroid：安卓独有的设置颜色纹理，需要安卓版本大于5.0
            gesturesEnabled：是否支持滑动返回手势，iOS默认支持，安卓默认关闭
         */
       
          //  headerTitle:'NULL',
           
        //     headerTitleStyle:{color:'white',fontSize:16,top:10,flex:1,textAlign: 'center'},
        //     headerBackTitleStyle:{color:'white',fontSize:16},
        //     headerStyle:{backgroundColor:'rgb(30,70,125)',color:'white',height:50,fontSize:16},
        //    // headerBackTitle:title,
        //     headerRight:<View/>,
        //     headerBackTitleStyle:{color:'white',marginBottom: 0,fontSize:16},
        //     headerTintColor:'#fff',
            gesturesEnabled:false  // 是否可以右滑返回
     
       };


   
    componentDidMount(){
        InteractionManager.runAfterInteractions(()=>{
           this.startAnimation()
        });

        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }



    }
    startAnimation(){
        if(this.state.show){
        this.state.anim.setValue(0)
        Animated.timing(this.state.anim,{
            toValue:1,
            duration:1500,
            easing:Easing.linear,
        }).start(()=>this.startAnimation());
        }
    }
    componentWillUnmount(){
        this.state.show = false;
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
        }
        
    }

    onBackAndroid = () => {

       
        // if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
        //     //最近2秒内按过back键，可以退出应用。
        //     return false;
        //   }
        //   this.lastBackPressed = Date.now();
        //   Alert.alert('再按一次退出');
         // return false;
       
        // const {routes} = this.props;
       
        // if (routers.length > 1) {
        // nav.pop();
        // return true;
        // }
        // return false;
    };


    //扫描二维码方法
    barcodeReceived = (e) =>{
        if(this.state.show){
            
            if (e) {
                
               if(e.data==="checkPeel")//
               {
                this.props.navigation.navigate('checkPeelResult');   

               }
                this.state.show = false;

            } else {
                Alert.alert(
                    '提示',
                    '扫描失败'
                    [{text:'确定'}]
                )
            }
        }
    }

    switchlight(){
        this.isLightOn=!this.isLightOn;
        if(this.isLightOn)
        {
            this.setState({lightOn:'on'});

        }else{
            this.setState({lightOn:'off'});

        }


    }

    render() {


        let imagEle=this.isLightOn? <Image style={styles.light}
                                           source={require('../../res/images/lighton.png')} >
                                     </Image>:<Image style={styles.light}
                                           source={require('../../res/images/lightoff.png')} >
                                     </Image>;

        return (
            <View style={styles.container}>
                {/*导航条*/}
                {/* {this.renderNavBar()} */}
                <Camera
                    ref={(cam) => {
                    this.camera = cam;
                  }}
                    torchMode={this.state.lightOn}
                    style={styles.preview}
                    aspect={this.state.camera.aspect}
                    onBarCodeRead={this.barcodeReceived.bind(this)}
                    barCodeTypes = {['qr','aztec','code128', 'code39', 'code39mod43', 'code93', 'ean13', 'ean8', 'pdf417', 'upce', 'interleaved2of5', 'itf14', 'datamatrix']}
                >
                <View style = {{height:(height-244)/5,width:width,backgroundColor:'rgba(0,0,0,0.5)',}}>
                </View>
                <View style={{flexDirection:'row'}}>
                        <View style={styles.itemStyle}/>
                            <View style={styles.rectangle}>
                            <View style={styles.row1}/>
                            <View style={styles.row2}/>
                            <View style={styles.row3}/>
                            <View style={styles.row4}/>
                            
                           
                                {/* //    source={require('../AssetsImages/code_bar.png')}
                                   > */}
                                  <Animated.View style={[styles.animatiedStyle, {
                                                transform: [{
                                                    translateY: this.state.anim.interpolate({
                                                        inputRange: [0,1],
                                                        outputRange: [0,300]
                                                    })
                                                }]
                                            }]}>
                                </Animated.View>
                            </View>
                        <View style={styles.itemStyle}/>
                    </View>
                    <View style={{flex:1,backgroundColor:'rgba(0, 0, 0, 0.5)',width:width,alignItems:'center'}}>
                        <Text style={styles.textStyle}>对准二维码自动检测</Text>      
                        <TouchableOpacity style={[styles.lightbase]} onPress={this.switchlight.bind(this)}>
                            {imagEle}
                             <Text style={styles.lightTxt}>轻触点亮</Text>
                         </TouchableOpacity >   
                    </View>
                    
                       
                </Camera>
            </View>
        );
    }


    // // 导航条
    // renderNavBar(){
    //     return(
    //         <View style={styles.navBarStyle}>
    //             <TouchableOpacity
    //                 onPress={()=>{this.props.navigator.pop()}}
    //                 style={styles.leftViewStyle}>
    //                 <Image source={{uri:'nav_return'}}
    //                        style={{height:20,width:20}} />
    //             </TouchableOpacity>
    //             <Text style={[styles.navTitleStyle,{marginTop:Platform.OS == 'ios'?12:0,fontSize:20}]}>
    //                 二维码
    //             </Text>
    //         </View>
    //     )
    // }
}

const styles = StyleSheet.create({
    itemStyle:{
        backgroundColor:'rgba(0,0,0,0.5)',
        width:(width-300)/2,
        height:300
    },
    textStyle:{
        color:'#fff',
        marginTop:10,
        fontWeight:'bold',
        fontSize:14
    },
    navTitleStyle: {
        color:'white',
        fontWeight:'bold',
    },
    navBarStyle:{ // 导航条样式
        height: Platform.OS == 'ios' ? 64 : 44,
        backgroundColor:'rgba(34,110,184,1.0)',
        // 设置主轴的方向
        flexDirection:'row',
        // 垂直居中 ---> 设置侧轴的对齐方式
        alignItems:'center',
        justifyContent:'center'
    },

    leftViewStyle:{
        // 绝对定位
        // 设置主轴的方向
        flexDirection:'row',
        position:'absolute',
        left:10,
        bottom:Platform.OS == 'ios' ? 15:12,
        alignItems:'center',
        width:30
    },
    animatiedStyle:{
        height:2,
        backgroundColor:'rgb(101,161,168)'
    },
    container: {
       
        flex:1,
   
    },
    preview: {
        flex: 1,
    },
    rectangle: {
        borderColor: 'rgb(101,161,168)',
        borderWidth:1,
      
        height: 300,
        width: 300,
    },
    row1:{//顺序是上，右，下，左
        height: 20,
        width: 20,
        borderTopWidth:5,
        borderLeftWidth:5,
        borderLeftColor: 'rgb(101,161,168)',
        borderTopColor: 'rgb(101,161,168)',


    },
    row2:{
        height: 20,
        width: 20,
        borderTopWidth:5,
        borderRightWidth:5,
        borderRightColor: 'rgb(101,161,168)',
        borderTopColor: 'rgb(101,161,168)',
        position:"absolute",
        top:0,
        alignSelf: 'flex-end',


    },
    row3:{
        height: 20,
        width: 20,
        borderBottomWidth:5,
        borderLeftWidth:5,
        borderLeftColor: 'rgb(101,161,168)',
        borderBottomColor: 'rgb(101,161,168)',
        alignSelf: 'flex-start',
        position:"absolute",
        bottom:0
       

    },
    row4:{
        height: 20,
        width: 20,
        borderBottomWidth:5,
        borderRightWidth:5,
        borderRightColor: 'rgb(101,161,168)',
        borderBottomColor: 'rgb(101,161,168)',
        alignSelf: 'flex-end',
        position:"absolute",
        bottom:0

    },
    lightbase:{
        top:40,
        alignContent: 'center',
        position:'absolute',
       


    },
    light:{
        //top:10,
        width:30,
       height:30,
       resizeMode:'contain',
       alignSelf: 'center',
       tintColor:'white'
       // position:'absolute',
       // width:40,
        //height:40


    },
    lightTxt:{
        color:'#fff',
        fontSize:10


    }
});
    

export default qrScanner;